package com.sky.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.LoginFailedException;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 * 提供用户登录接口
 */
@Slf4j
@RestController
@Api(tags = "C端-用户接口")
@RequestMapping("/user/user")
public class UserController {

    @Resource(name = "userServiceImpl")
    UserService userService;
    @Resource(name = "weChatProperties")
    WeChatProperties weChatProperties;

    /**
     * 用户登录
     * @param userLoginDTO 用户登录信息，包含微信授权码
     * @return 登录成功返回用户登录详情，包含token；登录失败抛出异常
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        // 通过微信code获取openid
        String openid = getOpenid(userLoginDTO.getCode());
        if (openid == null) throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        UserLoginVO userLoginVO = userService.login(openid);
        if (userLoginVO != null) log.info("用户'{}'登录成功", userLoginVO.getId());
        return Result.success(userLoginVO);
    }

    /**
     * 根据微信授权码获取用户OpenID
     * @param code 微信授权码，用于向微信服务器换取用户OpenID
     * @return 获取到的OpenID，如果获取失败返回null
     */
    private String getOpenid(String code) {
        // 构建向微信服务器发送请求的参数
        String URL = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> map = new HashMap<>();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");

        // 向微信服务器发送请求，获取响应JSON
        String json = HttpClientUtil.doGet(URL, map);
        JSONObject jsonObject = JSON.parseObject(json);

        // 解析JSON，返回OpenID
        return jsonObject.getString("openid");
    }

    /**
     * 退出
     *
     * @return 成功退出返回结果
     */
    @PostMapping("/logout")
    @ApiOperation(value = "用户退出")
    public Result<String> logout() {
        log.info("id为{}的用户退出了账号", BaseContext.getCurrentId());
        return Result.success();
    }

}
